<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
</head>
<body>
  <form action="http://localhost:8081/admin/user" enctype="multipart/form-data" method="post" id="form">
    <input type="text" name="username"><br>
    <input type="text" name="pwd"><br>
    <input type="file" name="profileFile" accept="image/png,image/jpeg" id="fileInput"><br>
    <input type="submit" value="提交" id="submitBtn">
  </form>
  <img id="preImg" src="" alt="" width="100">

  <script>
    const formEle = document.getElementById('form')
    formEle.onsubmit = (e) => {
      e.preventDefault()

      const formData = new FormData(formEle)
      console.log(formData.get('username'))
      console.log(formData.get('pwd'))
      console.log(formData.get('profileFile'))

      axios({
        url: 'http://localhost:8081/admin/user',
        method: 'post',
        data: formData
      })
    }

    const fileInput = document.getElementById('fileInput')
    const preImg = document.getElementById('preImg')
    // file输入框的change事件在选择了文件后触发
    fileInput.onchange = function (e) {

      // 文件输入框上的files是包含所有加载的文件对象的数组
      console.log(e.target.files[0]);

      // 创建读取文件的fileReader对象
      const fileReader = new FileReader();

      // reader上有一个readAsDataURL方法 可以把文件读成base64的字符串, 并保存到result属性上
      fileReader.readAsDataURL(this.files[0]);

      // 绑定读取完成的事件
      fileReader.onload = function () {
        // 将加载的图片显示到页面上 => 图片预览效果
        document.getElementById('preImg').src = fileReader.result;
      }
    }
  </script>

</body>
</html>